package com.ld.oauth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;

/**
 * 资源服务器相关配置类
 */
@Configuration
@EnableResourceServer//开启资源服务器 请求服务的资源就必须要带token
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启方法级别权限控制
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    public static final String RESOURCE_ID = "auth-server";

    @Autowired
    private TokenStore tokenSTore;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        //当前资源服务器的资源id 认证服务器会认证客户端有没有这个资源id
        resources.resourceId(RESOURCE_ID)
                //本地形式的解析token
                .tokenStore(tokenSTore);
//                .tokenServices(tokenService());
    }

//    public ResourceServerTokenServices tokenService() {
//        //远程认证服务器进行校验token是否有效
//        RemoteTokenServices service = new RemoteTokenServices();
//        //远程认证服务器校验地址 默认是不允许访问的 要在认证服务器开启访问权限
//        service.setCheckTokenEndpointUrl("http://127.0.0.1:8000/auth/oauth/check_token");
//        service.setClientId("ld-pc");
//        service.setClientSecret("ld-secret");
//        return service;
//    }

    /**
     * 配置oauth2的scope的权限范围
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        //这个设置让springsecurity不会去使用和创建httpsession实例
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //所有请求都需要有all范围
                //这个代码是从上往下的去判断的
                //.antMatchers("/product/list").hasAuthority("product")//这个是针对用户所有用的permission里面的code
                .antMatchers("/**").access("#oauth2.hasScope('all')");
    }
}
